import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Toast } from 'vant';
Vue.use(VueRouter)


// 导入组件
// import MyLogin from '@/views/MyLogin'
// import layout from '@/views/Layout'
// import MyHome from '@/views/MyHome'
// import MyAsk from '@/views/MyAsk'
// import MyVideo from '@/views/MyVideo'
// import MyMine from '@/views/MyMine'
// import edit from '@/views/MyMine/edit'
// import MyArticle from '@/views/MyArticle'
// import MySearch from '@/views/MySearch'
// import result from '@/views/MySearch/result'
// import chat from '@/views/MyMine/chat'

// 导入组件 -- 懒加载形式
const MyLogin = () => import('@/views/MyLogin')
const layout = () => import('@/views/Layout')
const MyHome = () => import('@/views/MyHome')
const MyAsk = () => import('@/views/MyAsk')
const MyVideo = () => import('@/views/MyVideo')
const MyMine = () => import('@/views/MyMine')
const edit = () => import('@/views/MyMine/edit')
const MyArticle = () => import('@/views/MyArticle')
const MySearch = () => import('@/views/MySearch')
const result = () => import('@/views/MySearch/result')
const chat = () => import('@/views/MyMine/chat')

// 路由规则
const routes = [
  // 路由重定向：如果路径上什么都不输入，那么会自动重定向到/login路径
  { path: '', redirect: '/layout/home' },
  // 登录
  { name: 'MyLogin', path: '/login', component: MyLogin },
  { name: 'edit', path: '/mine/edit', component: edit },
  { name: 'MyArticle', path: '/article', component: MyArticle },
  { name: 'MySearch', path: '/search', component: MySearch },
  { name: 'result', path: '/search/result', component: result },
  { name: 'chat', path: '/mine/chat', component: chat },

  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      // 不加/拼接父路由的路径
      {
        name: 'MyHome',
        path: 'home',
        component: MyHome,
        meta: {
          needKeep: true
        }
      },
      { name: 'MyAsk', path: 'ask', component: MyAsk },
      { name: 'MyVideo', path: 'video', component: MyVideo },
      {
        name: 'MyMine',
        path: 'mine',
        component: MyMine,
        meta: {
          needLogin: true
        }
      }
    ]
  },
]

const router = new VueRouter({
  routes
})


// 全局前置守卫
router.beforeEach((to, from, next) => {

  // 判断要去的路由是不是一个需要登录的页面
  if (to.meta.needLogin) {

    // 要登录的页面先判断有没有登录
    if (store.state.tokenObj.token) {
      // 有token就给你放行
      next()

    } else {

      // 没有登录，就放行到登录页
      Toast('请先登录')
      // 打回登录页，并且记录我原本想去的页面的路径
      next({
        name: 'MyLogin',
        query: {
          // 记录我原本想去的页面的路径
          back: to.path
        }
      })
    }

  } else {

    // 不需要登录的页面，直接放行
    next()
  }
})

// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
